import { message } from 'antd';
import {
  getManageList,
  addManage,
  deleteManage,
  updateManage,
  roleSelect,
  manageSelect,
} from './service';

const Model = {
  namespace: 'smManageRule',
  state: {
    manageListData: {},
    tableRef: {},
    roleSelectData: [],
    mainSelectData: [],
  },
  effects: {
    *getManageList({ payload, resolve }, { call, put }) {
      const params = {
        ...payload,
        pageNum: payload.current,
        pageSize: payload.pageSize,
      };
      delete params.current;

      const response = yield call(getManageList, params);
      if (!response.error) {
        const { records, pageNum, total } = response;
        const result = {
          data: records,
          page: pageNum,
          pageSize: payload.pageSize,
          success: true,
          total,
        };
        resolve && resolve(result);
        yield put({
          type: 'save',
          payload: {
            manageListData: result,
          },
        });
      }
    },

    *roleSelect({ resolve }, { call, put }) {
      const response = yield call(roleSelect);
      if (!response.error) {
        const result = {
          data: response,
          success: true,
        };
        resolve && resolve(result);
        yield put({
          type: 'save',
          payload: {
            roleSelectData: result.data,
          },
        });
      }
    },

    *manageSelect({ payload }, { call, put }) {
      const params = {
        ...payload,
      };
      const response = yield call(manageSelect, params);
      if (!response.error) {
        yield put({
          type: 'save',
          payload: {
            mainSelectData: response,
          },
        });
      }
    },

    *addManage({ payload, resolve }, { call, put }) {
      const response = yield call(addManage, payload);
      if (!response.error) {
        resolve && resolve(response);
        message.success('角色新增成功！');
        yield put({
          type: 'tableReload',
        });
      }
    },
    *updateManage({ payload, resolve }, { call, put }) {
      const response = yield call(updateManage, payload);

      if (!response.error) {
        resolve && resolve(response);
        message.success('修改角色信息成功！');

        yield put({
          type: 'tableReload',
        });
      }
    },
    *deleteManage({ payload }, { call, put }) {
      const params = {
        id: payload[0],
      };
      const response = yield call(deleteManage, params);
      if (!response.error) {
        message.success('角色删除成功！');
        yield put({
          type: 'tableReload',
        });
      }
    },
  },
  reducers: {
    save(state, { payload }) {
      return { ...state, ...payload };
    },
    tableReload(state) {
      const tableRef = state.tableRef || {};
      setTimeout(() => {
        tableRef.current.reloadAndRest();
      }, 0);
      return { ...state };
    },
  },
};
export default Model;
